<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      ></el-alert>
      <!-- 级联选择框 -->
      <div class="cas_container">
        选择商品分类:
        <el-cascader
          v-model="selectKeys"
          :options="cateList"
          :props="CascaderProps"
          @change="handleChange"
          clearable
        ></el-cascader>
      </div>
      <!-- Tabs选项卡 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            size="mini"
            type="primary"
            :disabled="isDisable"
            @click="addAttributeVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyDate" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环展示的tag标签 -->
                <!-- {{scope.row.attr_vals}} -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="removeTag(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 按钮和输入框的切换区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引号 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <!-- 操作项 -->
            <el-table-column prop="name" label="操作">
              <template v-slot="scope">
                <!-- {{scope.row}} -->
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editQueryParam(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="isDisable"
            @click="addAttributeVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyDate" style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环展示的tag标签 -->
                <!-- {{scope.row.attr_vals}} -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="removeTag(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 按钮和输入框的切换区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引号 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <!-- 操作项 -->
            <el-table-column prop="name" label="操作">
              <template v-slot="scope">
                <!-- {{scope.row}} -->
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editQueryParam(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加属性/参数的对话框 -->
      <el-dialog
        :title="'添加' + Text"
        :visible.sync="addAttributeVisible"
        width="50%"
        @close="addFormClosed"
      >
        <!-- 表单区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRoules"
          ref="addAttributeRef"
          label-width="80px"
        >
          <el-form-item :label="Text" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addAttributeVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改属性/参数的对话框 -->
      <el-dialog
        :title="'修改' + Text"
        :visible.sync="editAttributeVisible"
        width="50%"
        @close="editFormClosed"
      >
        <!-- 表单区域 -->
        <el-form
          :model="editForm"
          :rules="addFormRoules"
          ref="editAttributeRef"
          label-width="80px"
        >
          <el-form-item :label="Text" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editAttributeVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择框选中的数据存放的数组
      selectKeys: [],
      // 级联选择框的数据源
      cateList: [],
      CascaderProps: {
        // 用户看到的字段
        label: 'cat_name',
        // 触发状态
        expandTrigger: 'hover',
        // 父子关联节点
        children: 'children',
        // 提交给后台的 id数据
        value: 'cat_id'
      },
      //tabs选项卡的激活面板
      activeName: 'many',
      // 动态参数列表数据
      manyDate: [],
      // 静态属性参数列表数据
      onlyDate: [],
      // 添加属性/参数的对话框的布尔值
      addAttributeVisible: false,
      // 修改属性/参数的对话框的布尔值
      editAttributeVisible: false,
      // 添加的表单对象
      addForm: {
        attr_name: ''
      },
      // 修改的表单对象
      editForm: {},
      // 添加的校验规则
      addFormRoules: {
        attr_name: [
          { required: true, message: '请输入必填信息', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置表单
    addFormClosed() {
      this.$refs.addAttributeRef.resetFields()
    },

    // 获取分类数据的方法
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败')
      }
      this.cateList = res.data
    },
    // 级联选择框触发的事件
    handleChange() {
      //   console.log(this.selectKeys);
      // 当将级联选择框清空之后,不再展示表格中的数据
      if (this.selectKeys.length == 0) {
        return (this.manyDate = this.manyDate = [])
      }
      this.getParamsList()
    },
    // 获取参数数据
    async getParamsList() {
      // 只允许为第三级分类设置相关参数;
      if (this.selectKeys.length !== 3) {
        return (this.selectKeys = [])
      }
      const { data: res } = await this.$http.get(
        `categories/${this.selectKeys[2]}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      console.log(res)

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // 要在展开行中渲染对个tag标签,需要将data中的attr_vals以空格分隔,转换为数组
      res.data.forEach(item => {
        // console.log(item);
        item.attr_vals = item.attr_vals.length ? item.attr_vals.split(' ') : []

        // 因为输入框和新增tag切换不能共享data中独一份数据,在遍历的时候手动为每一项添加自己的布尔值和value值
        item.inputValue = ''
        item.inputVisible = false
      })

      // 根据激活面板的不同,将不同的数据挂载在不同的数据源上
      this.activeName == 'many'
        ? (this.manyDate = res.data)
        : (this.onlyDate = res.data)
    },
    // 添加属性/参数
    addParams() {
      this.$refs.addAttributeRef.validate(async boo => {
        if (!boo) {
          return this.$message.error('请输入必须参数')
        }
        const { data: res } = await this.$http.post(
          `categories/${this.selectKeys[2]}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')

        // 获取参数列表
        this.getParamsList()
        // 关闭对话框
        this.addAttributeVisible = false
      })
    },
    // tabs切换回触发的事件
    handleClick() {
      //   console.log(this.activeName);
      this.getParamsList()
    },
    // 重置修改的表单数据
    editFormClosed() {
      this.$refs.editAttributeRef.resetFields()
    },
    // 点击编辑按钮显示表单数据
    async editQueryParam(attrId) {
      console.log(attrId)
      // 查询当前的参数信息
      const { data: res } = await this.$http.get(
        `categories/${this.selectKeys[2]}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      this.editForm = res.data

      this.editAttributeVisible = true
    },
    // 编辑提交
    editParams() {
      // 预校验
      this.$refs.editAttributeRef.validate(async boo => {
        if (!boo) {
          return this.$message.error('请输入必要信息')
        }
        // 发送请求
        const { data: res } = await this.$http.put(
          `categories/${this.selectKeys[2]}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新信息失败')
        }
        this.$message.success('更新信息成功')

        // 重新加载数据
        this.getParamsList()
        // 关闭对话框
        this.editAttributeVisible = false
      })
    },
    // 删除用户信息
    async deleteParams(id) {
      console.log(id)
      // 提示对话框
      const res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // confirm 表示点击的是确认按钮
      // cancel  表示点击的是取消按钮
      if (res != 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 发送删除的请求
      const { data: result } = await this.$http.delete(
        `categories/${this.selectKeys[2]}/attributes/${id}`
      )
      console.log(result)
      if (result.meta.status !== 200) {
        return this.$message.error('删除用户失败,请稍后重试')
      }
      this.$message.success('删除用户成功')
      // 重新加载数据
      this.getParamsList()
    },
    //
    handleInputConfirm(row) {
      // 非空校验
      if (!row.inputValue.trim().length) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      // 一定放在代码的最前面
      row.attr_vals.push(row.inputValue.trim())
      // 调用方法
      this.saveParams(row)
      row.inputVisible = false
      //追加后清空
      row.inputValue = ''
    },
    showInput(row) {
      row.inputVisible = true
      // 等待dom元素重新更新到页面上才会触发的函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 发送新增tag属性的方法
    async saveParams(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.selectKeys[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('操作失败')
      }
      this.$message.success('操作成功')
    },
    // tag标签的移除事件
    removeTag(i, row) {
      console.log(i, row.attr_vals)
      // 截取数组
      row.attr_vals.splice(i, 1)
      // 调用方法
      this.saveParams(row)
    }
  },
  computed: {
    // 按钮是否禁用的计算属性
    isDisable() {
      return this.selectKeys.length == 3 ? false : true
    },
    // 根据激活面板的不同返回不同的字符
    Text() {
      return this.activeName == 'many' ? '动态参数' : '静态属性'
    }
  },
  created() {
    // 调用获取分类数据的方法
    this.getCateList()
  }
}
</script>

<style lang="less" scoped>
.cas_container {
  margin-top: 15px;
  margin-bottom: 10px;
}
.el-cascader {
  width: 260px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
